package com.nodecollege.cloud.client.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nodecollege.cloud.client.feign.ApiClient;
import com.nodecollege.cloud.client.feign.ApiVisitClient;
import com.nodecollege.cloud.client.service.ApiService;
import com.nodecollege.cloud.common.UpmsConstants;
import com.nodecollege.cloud.common.annotation.ApiAnnotation;
import com.nodecollege.cloud.common.aop.NCAop;
import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.model.NCResult;
import com.nodecollege.cloud.common.model.po.UpmsApi;
import com.nodecollege.cloud.common.model.po.UpmsApiVisit;
import com.nodecollege.cloud.common.utils.DateUtils;
import com.nodecollege.cloud.common.utils.RedisLock;
import com.nodecollege.cloud.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author LC
 * @date 2020/1/10 10:19
 */
@Slf4j
@Service
public class ApiServiceImpl implements ApiService {

    @Value("${spring.application.name:default}")
    private String applicationName;

    private String UPMS_API_LIST = "upms:apiList:" + applicationName;
    private String UPMS_API_VISIT_LIST = "upms:apiVisitList:" + applicationName + ":";

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Autowired
    private ApiClient apiClient;
    @Autowired
    private ApiVisitClient apiVisitClient;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisLock redisLock;

    /**
     * 项目启动时，自动查询用注解标记过的接口数据，并和数据库进行比对，有则更新，无则插入
     */
    @PostConstruct
    private void initApiList() {
        log.info("初始化查询api信息！");
        List<UpmsApi> annList = new ArrayList<>();
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();

        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : handlerMethods.entrySet()) {
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            ApiAnnotation apiAnnotation = method.getMethodAnnotation(ApiAnnotation.class);
            UpmsApi api = new UpmsApi();
            api.setApplicationName(applicationName);
            api.setControllerName(NCAop.getConciseMethodName(method.getMethod().getDeclaringClass().getName()));
            api.setApiUrl(info.getPatternsCondition().getPatterns().iterator().next());
            if (apiAnnotation != null) {
                api.setModularName(apiAnnotation.modularName());
                api.setDescription(apiAnnotation.description());
                api.setState(apiAnnotation.state());
            } else {
                api.setModularName(api.getControllerName());
                api.setDescription(api.getApiUrl());
                api.setState(UpmsConstants.API_NORMAL);
            }
            log.info("api信息 {}", api.toString());
            annList.add(api);
        }
        try {
            NCResult<UpmsApi> result = apiClient.initApiList(annList);
            if (result.getSuccess()) {
                annList = result.getRows();
                redisUtils.set(UPMS_API_LIST, annList);
            } else {
                log.error(result.toString());
            }
        } catch (Exception e) {
            log.error("初始化接口信息失败！", e);
        }
    }

    /**
     * 添加接口访问记录到redis中
     *
     * @param upmsApiVisit
     */
    @Override
    public void addApiVisitCache(UpmsApiVisit upmsApiVisit) {
        log.debug("接口访问记录 {}", JSONObject.toJSONString(upmsApiVisit));
        // 1. 查出接口id
        List<UpmsApi> apiList = redisUtils.getList(UPMS_API_LIST, UpmsApi.class);
        if (apiList == null) {
            initApiList();
            apiList = redisUtils.getList(UPMS_API_LIST, UpmsApi.class);
            if (apiList == null) {
                return;
            }
        }
        for (int i = 0; i < apiList.size(); i++) {
            if (apiList.get(i).getApplicationName().equals(upmsApiVisit.getApplicationName())
                    && apiList.get(i).getControllerName().equals(upmsApiVisit.getControllerName())
                    && apiList.get(i).getApiUrl().equals(upmsApiVisit.getApiUrl())) {
                // 设置接口id
                upmsApiVisit.setApiId(apiList.get(i).getApiId());
                break;
            }
        }
        String dateH = DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN.YEAR_HOUR_FORMAT);
        String key = UPMS_API_VISIT_LIST + dateH + ":" + upmsApiVisit.getApiId() + ":" + upmsApiVisit.getTenantId()
                + ":" + upmsApiVisit.getAccessSource() + ":-" + upmsApiVisit.getRequestIp();

        redisUtils.increment(key, 1);
        log.debug("{} 访问量 {}", key, redisUtils.get(key, Long.class));
        log.debug("所有的key {}", redisUtils.keys(UPMS_API_VISIT_LIST + dateH + ":*"));
    }

    /**
     * 每小时第一分钟的时候将redis中的数据保存到数据库中，同时清空redis
     */
    @Scheduled(cron = "0 1 0/1 * * ? ")
    public void sync() {
        log.info("定时任务！！！！");
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        now.add(Calendar.HOUR, -1);
        String dateH = DateUtils.formatDate(now.getTime(), DateUtils.DATE_PATTERN.YEAR_HOUR_FORMAT);
        log.info("上一个小时的时间{}", dateH);
        try {
            if (redisLock.tryLock(dateH, NCConstants.LONG_30)) {
                List<UpmsApiVisit> list = getApiVisitListByDateH(dateH);
                apiVisitClient.addApiVisitList(list);
                redisUtils.delete(redisUtils.keys(UPMS_API_VISIT_LIST + dateH + ":*"));
            }
        } catch (Exception e) {
            log.error("定时保存接口访问记录任务执行出错！！！", e);
        } finally {
            redisLock.releaseLock(dateH, NCConstants.LONG_30);
        }
    }

    /**
     * 从redis中获取指定时间段的访问数据
     *
     * @param dateH
     * @return
     */
    private List<UpmsApiVisit> getApiVisitListByDateH(String dateH) {
        String key = UPMS_API_VISIT_LIST + dateH + ":*";
        List<UpmsApiVisit> list = new ArrayList<>();
        List<String> allKeys = new ArrayList<>(redisUtils.keys(key));
        for (int i = 0; i < allKeys.size(); i++) {
            String[] args = allKeys.get(i).split(":");
            if (args.length >= 5) {
                String date = args[2].substring(0, 8);
                String hh = args[2].substring(8);
                UpmsApiVisit visit = new UpmsApiVisit();
                visit.setVisitDate(date);
                visit.setVisitH(hh);
                visit.setApiId(Long.valueOf(args[3]));
                visit.setTenantId(NCConstants.NULL_STRING.equalsIgnoreCase(args[4]) ? null : Long.valueOf(args[4]));
                visit.setAccessSource(args[5]);
                visit.setRequestIp(allKeys.get(i).substring(allKeys.get(i).lastIndexOf("-") + 1));
                visit.setVisitCount(redisUtils.get(allKeys.get(i), Long.class));
                list.add(visit);
            }
        }
        log.debug("{} 时间段的访问数据 {}", dateH, JSONObject.toJSONString(list));
        return list;
    }
}
